package implementation1.app.commands;

import exceptions.CommandErrorFromUserException;
import exceptions.CommandException;
import exceptions.StreamEOFException;
import exceptions.StreamException;
import implementation1.app.Global;
import implementation1.app.streams.AccessAttributes;
import implementation1.app.streams.SendStream;
import interfaces.app.IProcess;
import interfaces.data.IHandle;

/**
 * Created: 1.12.11
 *
 * @author Martin Štulc (<a href="mailto:martin.stulc@gmail.com">martin.stulc@gmail.com</a>)
 * @version 1.0
 */
public class Receive extends Command
{
    /**
     * Default constructor.
     *
     * @param parent parent process over which is command processed
     * @param handle parameters of command
     */
    public Receive(IProcess parent, IHandle handle)
    {
        super(parent, handle);
    }

    @Override
    public void mainCommand(String[] args) throws CommandException
    {
        if (args == null || args.length != 0)
        {
            throw new CommandErrorFromUserException(bundle.getString("error.arguments.wrongCount"));
        }

        if (handle.getOut() == null)
        {
            throw new CommandException(bundle.getString("error.outputStream.empty"));
        }

        try
        {
            try
            {
                SendStream.getInstance().open(AccessAttributes.READ);
                openedStreamsOfProcess.add(SendStream.getInstance());
                String message = SendStream.getInstance().readLine();

                handle.getOut().open(AccessAttributes.WRITE);
                openedStreamsOfProcess.add(handle.getOut());
                handle.getOut().writeLine(message);
            } catch (StreamEOFException e)
            {
                /*no bug empty catch block*/
            }
        } catch (StreamException e)
        {
            throw new CommandException(e.getMessage());
        }
        finally
        {
            Global.closeStreamQuietly(handle.getOut());
            openedStreamsOfProcess.remove(handle.getOut());
            Global.closeStreamQuietly(SendStream.getInstance());
            openedStreamsOfProcess.remove(SendStream.getInstance());
        }
    }

    public String toString()
    {
        return "receive";
    }

}
